package com.ebt.m.customer.ui;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.ebt.m.R;
import com.ebt.m.customer.adapter.PicAdapter;
import com.ebt.m.customer.constant.Dictionary;
import com.ebt.m.customer.entity.Attachment;
import com.ebt.m.customer.entity.CompanyBean;
import com.ebt.m.customer.entity.PolicyBean;
import com.ebt.m.customer.entity.RiskBean;
import com.ebt.m.customer.event.EventCustomerRefresh;
import com.ebt.m.customer.event.OnAttachDeleteEvent;
import com.ebt.m.customer.event.OnCropEvent;
import com.ebt.m.customer.event.PolicyUpdateEvent;
import com.ebt.m.customer.net.http.OSSUploader;
import com.ebt.m.customer.net.http.PolicyHttps;
import com.ebt.m.customer.net.json.ErrorJson;
import com.ebt.m.customer.net.json.PolicyAllJson;
import com.ebt.m.customer.util.ImageProcessor;
import com.ebt.m.customer.util.PolicyAttachOpt;
import com.ebt.m.customer.view.ListDialog;
import com.ebt.m.customer.view.MenuForPolicyEdit;
import com.ebt.m.customer.view.NestedGridView;
import com.ebt.m.utils.ImageSelectUtil;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.UIHelper;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 保单编辑
 * Created by archer.qi on 2016/12/7.
 */
public class PolicyEditActivity extends Activity implements View.OnClickListener, ListDialog.onMenuSelectListener, AdapterView.OnItemClickListener {

    public static final String ARG_FLAG = "Flag";
    public static final String ARG_CUSTOMER_ID = "CustomerId";
    public static final String ARG_DATA = "PolicyData";

    private TextView mTvTitle;
    private TextView mTvComplete;
    private ImageView mBtnBack;
    private NestedGridView mGridPics;

    private MenuForPolicyEdit menuBrand; // 品牌
    private MenuForPolicyEdit menuRisk; // 主约
    private MenuForPolicyEdit menuPermium; // 总保费
    private MenuForPolicyEdit menuPostNo; // 投保单号
    private MenuForPolicyEdit menuPolicyNo; // 保单号
    private MenuForPolicyEdit menuPayMode; // 缴费方式
    private MenuForPolicyEdit menuEffectDate; // 生效日期

    /*  菜单项与必填菜单项*/
    private List<MenuForPolicyEdit> mMenus = new ArrayList<>();
    private List<MenuForPolicyEdit> mMustFillMenus = new ArrayList<>();
    private List<MenuForPolicyEdit> mFlashMenus = new ArrayList<>();

    /* 0-创建模式, 1-编辑模式 */
    private int MODE = 0;

    /* 选择缴费方式*/
    private ListDialog listDialog;

    private DatePickerDialog mDatePicker;

    /*  附件*/
    private PicAdapter mPicAdapter;

    /* 该页面的数据类*/
    private PolicyBean policyData;
    private String customerId;

    // 添加附件
    private ImageProcessor processor;
    // 上传结果统计
    private int uploadCount;
    // 附件是否删除完成
    private boolean deleteComplete;
    // 附件是否创建完成
    private boolean createComplete;
    // 临时保存上传成功的附件，用于提交
    private List<Attachment> mTempAttachmentsUploaded = new ArrayList<>();
    // 点击完成，正在处理...
    private boolean doClicking;

    /* 闪烁统计，0时停止，闪烁依次为黄->白->黄->白*/
    private int flashCount = 4;
    // 闪烁间隔
    private long flashInterval = 500;

    private static final int REQUEST_CODE_CHOOSE = 0x000000ff;

    /*  必填项检查-闪烁*/
    private Handler flashHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (flashCount == 0) {
                // 停止
                UIHelper.makeToast(PolicyEditActivity.this, "请填写必填选项");
                flashCount = 4;
                doClicking = false;
                return;
            }

            flashCount--;

            if (msg.what == 0) {
                // 白色背景
                flash(0);
                flashHandler.sendEmptyMessageDelayed(1, flashInterval);
            } else if (msg.what == 1) {
                // 黄色背景
                flash(1);
                flashHandler.sendEmptyMessageDelayed(0, flashInterval);
            }
        }
    };

    /*完成统计：统计是否上传与删除操作都完成*/
    private Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: // 附件上传
                    uploadCount--;
                    createAttachmentsWhenCount0();
                    break;
                case 1: // 附件删除
                    deleteComplete = true;
                    ifCompleteWhenAttachmentDeleted();
                    break;
                case 2: // 附件创建
                    createComplete = true;
                    ifCompleteWhenAttachmentCreated();
                    break;
            }
        }

        /*上传统计为0<上传完成> 创建附件...*/
        private void createAttachmentsWhenCount0() {
            if (uploadCount == 0) {
                // 所有附件上传成功，执行CustomerPolicyCreate
                if (mTempAttachmentsUploaded.size() > 0) {
                    Logger.i("->开始创建");
                    createPolicyAttachments(policyData.getPolicyId(), mTempAttachmentsUploaded);
                } else {
                    // 如果所有附件上传失败，则发送到附件创建完成
                    updateHandler.sendEmptyMessage(2);
                }
            }
        }

        /*创建附件完成*/
        private void ifCompleteWhenAttachmentCreated() {
            if (MODE == 0) {
                // 如果是创建菜单，提交结束则菜单创建结束
                onComplete();
            } else if (MODE == 1) {
                // 如果附件删除已经完成了，或者不需要删除
                if (deleteComplete) {
                    onComplete();
                }
            }
        }

        /*删除完成*/
        private void ifCompleteWhenAttachmentDeleted() {
            if (MODE == 1) {
                // 更新保单同时判断上传与删除是否都完成
                if (createComplete) {
                    onComplete();
                }
            }
        }

        private void onComplete() {
            if (MODE == 0) {
                UIHelper.makeToast(PolicyEditActivity.this, "创建保单完成");
                EventBus.getDefault().post(new PolicyUpdateEvent(0, policyData.getPolicyId()));
                EventBus.getDefault().post(new EventCustomerRefresh(customerId));
            } else if (MODE == 1) {
                UIHelper.makeToast(PolicyEditActivity.this, "更新保单完成");
                EventBus.getDefault().post(new PolicyUpdateEvent(1, policyData.getPolicyId()));
                EventBus.getDefault().post(new EventCustomerRefresh(customerId));
            }
            finish();
            doClicking = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_policy_edit);
        initViews();
        init();
    }

    private View v(int id) {
        return findViewById(id);
    }

    private void initViews() {
        mTvTitle = (TextView) v(R.id.policy_details_title);
        mTvComplete = (TextView) v(R.id.policy_details_complete);
        mBtnBack = (ImageView) v(R.id.policy_details_back);
        mGridPics = (NestedGridView) v(R.id.policy_details_picGallery);

        menuBrand = (MenuForPolicyEdit) v(R.id.policy_details_brand);
        menuBrand.setContentEnabled(false);
        mMustFillMenus.add(menuBrand);

        menuRisk = (MenuForPolicyEdit) v(R.id.policy_details_mainRisk);
        menuRisk.setContentEnabled(false);
        mMustFillMenus.add(menuRisk);

        menuPermium = (MenuForPolicyEdit) v(R.id.policy_details_totalCost);
        menuPermium.setInputNumberOnly();
        menuPermium.setUnit("元");
        menuPermium.setDecimalAllowInput(2);
        mMenus.add(menuPermium);

        menuPostNo = (MenuForPolicyEdit) v(R.id.policy_details_riskNo);
        mMenus.add(menuPostNo);

        menuPolicyNo = (MenuForPolicyEdit) v(R.id.policy_details_policyNo);
        mMenus.add(menuPolicyNo);

        menuPayMode = (MenuForPolicyEdit) v(R.id.policy_details_payMode);
        menuPayMode.setContentEnabled(false);
        mMustFillMenus.add(menuPayMode);

        menuEffectDate = (MenuForPolicyEdit) v(R.id.policy_details_effect);
        menuEffectDate.setContentEnabled(false);

        mBtnBack.setOnClickListener(this);
        mTvComplete.setOnClickListener(this);
        menuBrand.setOnClickListener(this);
        menuRisk.setOnClickListener(this);
        menuPayMode.setOnClickListener(this);
        menuEffectDate.setOnClickListener(this);

        mGridPics.setOnItemClickListener(this);
    }

    /* 切换模式 */
    private void switchMode() {
        switch (MODE) {
            case 0:
                // 新建
                mTvTitle.setText("新建保单");
                break;
            case 1:
                // 编辑
                mTvTitle.setText("编辑保单");
                break;
        }
    }

    private void init() {
        Bundle args = getIntent().getExtras();
        if (args != null) {
            if (args.containsKey(ARG_FLAG)) {
                MODE = args.getInt(ARG_FLAG);
            }
            if (args.containsKey(ARG_DATA)) {
                policyData = (PolicyBean) args.getSerializable(ARG_DATA);
            } else {
                policyData = new PolicyBean();
                if (args.containsKey(ARG_CUSTOMER_ID)) {
                    customerId = args.getString(ARG_CUSTOMER_ID);
                    policyData.setCustomerId(customerId);
                    policyData.setEffectDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                }
            }
        }

        EventBus.getDefault().register(this);

        switchMode();
        setData();
    }

    private void setData() {
        if (policyData == null) {
            return;
        }

        // 公司
        CompanyBean company = policyData.getCompany();
        if (company != null) {
            if (TextUtils.isEmpty(company.getShortName())) {
                if (TextUtils.isEmpty(company.getName())) {
                    menuBrand.setContent(company.getName());
                }
            } else {
                menuBrand.setContent(company.getShortName());
            }
        }

        // 主约
        RiskBean risk = policyData.getRisk();
        if (risk != null) {
            if (TextUtils.isEmpty(risk.getShortName())) {
                if (TextUtils.isEmpty(risk.getName())) {
                    menuRisk.setContent(risk.getName());
                }
            } else {
                menuRisk.setContent(risk.getShortName());
            }
        }

        // 保费
        String permiumValue = NumberFormat.getInstance().format(policyData.getPermium()).replace(",", "");
        menuPermium.setContent(permiumValue);

        // 投保单号
        if (!TextUtils.isEmpty(policyData.getInsureNo())) {
            menuPostNo.setContent(policyData.getInsureNo());
        }

        // 保单号
        if (!TextUtils.isEmpty(policyData.getPolicyNo())) {
            menuPolicyNo.setContent(policyData.getPolicyNo());
        }

        // 缴费方式
        if (!TextUtils.isEmpty(policyData.getPayMode())) {
            menuPayMode.setContent(policyData.getPayMode());
        }

        //生效日期
        if (!TextUtils.isEmpty(policyData.getEffectDate())) {
            menuEffectDate.setContent(policyData.getEffectDate());
        }

        setGridAdapter();
    }

    private void setGridAdapter() {
        List<Attachment> dataNotDeleted = filterDataShown();
        mPicAdapter = new PicAdapter(this, dataNotDeleted, true);
        mGridPics.setAdapter(mPicAdapter);
    }

    /**
     * Attachment.option = -1， 说明已经删除，不作显示过滤
     *
     * @return
     */
    private List<Attachment> filterDataShown() {
        if (policyData == null) {
            return null;
        }
        if (policyData.getAttachments() == null) {
            return null;
        }
        if (policyData.getAttachments().size() == 0) {
            return policyData.getAttachments();
        }
        List<Attachment> filteredData = new ArrayList<>();
        for (Attachment attach :
                policyData.getAttachments()) {
            if (attach.option > -1) {
                filteredData.add(attach);
            }
        }
        return filteredData;
    }

    /**
     * 显示弹窗 - 选择
     *
     * @param data
     */
    private void showDialog(int flag, List<String> data) {
        if (listDialog == null) {
            listDialog = new ListDialog(PolicyEditActivity.this);
        }
        listDialog.show();
        listDialog.setData(data);
        listDialog.setFlag(flag);
        listDialog.addOnItemClickListener(this);
    }

    /**
     * 检查必填项是否存在空
     *
     * @return
     */
    private boolean isMustFillNull() {
        boolean isMustFillNull = false;
        mFlashMenus.clear();

        if (TextUtils.isEmpty(menuBrand.getContent())) {
            isMustFillNull = true;
            mFlashMenus.add(menuBrand);
        } else {
            if ("请选择保险公司".equals(menuBrand.getContent())) {
                // 默认hint视为null
                isMustFillNull = true;
                mFlashMenus.add(menuBrand);
            }
        }

        if (TextUtils.isEmpty(menuRisk.getContent())) {
            isMustFillNull = true;
            mFlashMenus.add(menuRisk);
        } else {
            if ("请选择主约".equals(menuRisk.getContent())) {
                // 默认hint视为null
                isMustFillNull = true;
                mFlashMenus.add(menuRisk);
            }
        }

        if (TextUtils.isEmpty(menuPermium.getContent())) {
            isMustFillNull = true;
            mFlashMenus.add(menuPermium);
        }

        if (TextUtils.isEmpty(menuPayMode.getContent())) {
            isMustFillNull = true;
            mFlashMenus.add(menuPayMode);
        } else {
            if ("请选择".equals(menuPayMode.getContent())) {
                // 默认hint视为null
                isMustFillNull = true;
                mFlashMenus.add(menuPayMode);
            }
        }

        return isMustFillNull;
    }

    /**
     * 提交检查
     */
    private void doCheck() {
        if (isMustFillNull()) {
            // 如果有必填选项未填写
            flashHandler.sendEmptyMessage(1);
        } else {
            String value = menuPermium.getContent();
            double doubleValue;
            if (value == null || value.length() == 0) {
                doubleValue = 0.0;
            } else {
                doubleValue = Double.parseDouble(value);
            }

            if (doubleValue > 100000000) {
                UIHelper.makeToast(this, "保费整数位不能超过9位");
                doClicking = false;
                return;
            }

            getData();
            doPolicyRequest();
        }
    }

    private void getData() {
        if (menuPermium.getContent().isEmpty()) {
            policyData.setPermium(0);
        } else {
            policyData.setPermium(Double.parseDouble(menuPermium.getContent()));
        }
        policyData.setPolicyNo(menuPolicyNo.getContent());
        policyData.setInsureNo(menuPostNo.getContent());
        policyData.setPayMode(menuPayMode.getContent());
        policyData.setEffectDate(menuEffectDate.getContent());
        if (policyData.getAttachments() == null) {
            policyData.setAttachments(new ArrayList<>());
        }
    }

    /**
     * 执行请求：｛保单创建、更新｝
     */
    private void doPolicyRequest() {
        if (MODE == 0) {
            // 创建保单
            createCustomerPolicy();
        } else if (MODE == 1) {
            // 更新保单
            updateCustomerPolicy();
        }
    }


    /**
     * 获取需要上传的部分附件
     *
     * @return
     */
    private List<Attachment> getUploadAttachments() {
        if (policyData == null) {
            return null;
        }
        if (policyData.getAttachments() == null || policyData.getAttachments().size() == 0) {
            return null;
        }
        List<Attachment> mUploadAttaches = new ArrayList<>();
        for (Attachment attach :
                policyData.getAttachments()) {
            if (attach != null) {
                if (attach.option == 1) {
                    mUploadAttaches.add(attach);
                }
            }
        }
        return mUploadAttaches;
    }

    /**
     * 获取需要删除的部分附件
     *
     * @return
     */
    private List<Attachment> getDeleteAttachments() {
        if (policyData == null) {
            return null;
        }
        if (policyData.getAttachments() == null || policyData.getAttachments().size() == 0) {
            return null;
        }
        List<Attachment> mDeleteAttaches = new ArrayList<>();
        for (Attachment attach :
                policyData.getAttachments()) {
            if (attach != null) {
                if (attach.option == -1) {
                    mDeleteAttaches.add(attach);
                }
            }
        }
        return mDeleteAttaches;
    }

    /**
     * 根据path查找上传完成的附件，加入到Create集合
     *
     * @param path
     */
    private void addAttachmentUploaded(String path) {
        if (policyData == null || TextUtils.isEmpty(path)) {
            return;
        }
        if (policyData.getAttachments() != null && policyData.getAttachments().size() > 0) {
            for (Attachment a :
                    policyData.getAttachments()) {
                if (a != null && a.getPath() != null) {
                    if (a.getPath().equals(path)) {
                        mTempAttachmentsUploaded.add(a);
                    }
                }
            }
        }


    }

    /**
     * 上传文件到阿里云
     */
    private void uploadMultiAttach2AliYun(String policyId, List<Attachment> uploadEntitys) {
        OSSUploader.init(PolicyEditActivity.this.getApplicationContext());
        OnOSSUploadResponseListener lis = new OnOSSUploadResponseListener();
        OSSUploader.uploadMultiAttachments(uploadEntitys, new OnOSSUploadResponseListener());
    }

    /**
     * 创建保单附件
     *
     * @param policyId
     * @param attches
     */
    private void createPolicyAttachments(String policyId, List<Attachment> attches) {
        PolicyHttps.getInstance(this.getApplicationContext()).createPolicyAttachment(policyId, attches, new PolicyHttps.onResponseCallback() {
            @Override
            public void onResponse(PolicyAllJson data) {
                Logger.i("->创建保单附件成功...");
                updateHandler.sendEmptyMessage(2);
            }

            @Override
            public void onError(ErrorJson error) {
                Logger.i("->创建保单附件失败...");
                updateHandler.sendEmptyMessage(2);
            }

            @Override
            public void onFailure(Throwable t) {
                Logger.i("->创建保单附件异常...");
                updateHandler.sendEmptyMessage(2);
            }
        });
    }

    /**
     * 删除附件
     *
     * @param policyId
     * @param attches
     */
    private void deletePolicyAttachments(String policyId, List<Attachment> attches) {
        PolicyHttps.getInstance(this.getApplicationContext()).deletePolicyAttachment(policyId, attches, new PolicyHttps.onResponseCallback() {
            @Override
            public void onResponse(PolicyAllJson data) {
                Logger.i("->删除保单附件成功...");
                updateHandler.sendEmptyMessage(1);
            }

            @Override
            public void onError(ErrorJson error) {
                Logger.i("->删除保单附件失败...");
                updateHandler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(Throwable t) {
                Logger.i("->删除保单附件异常...");
                updateHandler.sendEmptyMessage(1);
            }
        });
    }

    /**
     * 找到上传Path = path的附件，设置Url
     *
     * @param url
     * @param path
     */
    private void setAttachUrl(String url, String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (policyData.getAttachments() == null) {
            return;
        }
        List<Attachment> attaches = policyData.getAttachments();
        int length = attaches.size();

        for (int i = 0; i < length; i++) {
            if (attaches.get(i) != null && path.equals(attaches.get(i).getPath())) {
                policyData.getAttachments().get(i).setUrl(url);
            }
        }
    }

    /**
     * 上传附件到阿里云服务器监听
     */
    private class OnOSSUploadResponseListener implements OSSCompletedCallback<PutObjectRequest, PutObjectResult> {

        @Override
        public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
            Logger.i("++++上传到阿里云成功++++");
            if (putObjectRequest != null) {
                addAttachmentUploaded(putObjectRequest.getUploadFilePath());
                String url = OSSUploader.getPublicUrl(putObjectRequest.getBucketName(), putObjectRequest.getObjectKey());
                Logger.i("上传附件Url = " + url);
                setAttachUrl(url, putObjectRequest.getUploadFilePath());
            }
            updateHandler.sendEmptyMessage(0);
        }

        @Override
        public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
            Logger.i("++++上传阿里云服务器失败++++");
            updateHandler.sendEmptyMessage(0);
            // 请求异常
            if (e != null) {
                // 本地异常如网络异常等
                e.printStackTrace();
            }
            if (e1 != null) {
                // 服务异常
                Log.e("ErrorCode", e1.getErrorCode());
                Log.e("RequestId", e1.getRequestId());
                Log.e("HostId", e1.getHostId());
                Log.e("RawMessage", e1.getRawMessage());
            }
        }
    }

    /**
     * 创建保单请求
     */
    private void createCustomerPolicy() {
        PolicyHttps.getInstance(this.getApplicationContext()).createCustomerPolicy(policyData, new PolicyHttps.onResponseCallback() {
            @Override
            public void onResponse(PolicyAllJson data) {
                Logger.i("->创建保单成功...");
                if (data != null && !TextUtils.isEmpty(data.policyId)) {
                    policyData.setPolicyId(data.policyId);
                    // 上传保单附件
                    List<Attachment> uploadEntitys = policyData.getAttachments();
                    if (uploadEntitys != null && uploadEntitys.size() > 0) {
                        uploadCount = uploadEntitys.size();
                        uploadMultiAttach2AliYun(data.policyId, uploadEntitys);
                    } else {
                        // 如果没有附件，则同发送到提交结束
                        updateHandler.sendEmptyMessage(2);
                    }
                }

            }

            @Override
            public void onError(ErrorJson error) {
                if (error != null) {
                    UIHelper.makeToast(PolicyEditActivity.this, error.message);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                UIHelper.makeToast(PolicyEditActivity.this, "创建保单失败");
            }
        });
    }

    /**
     * 更新保单请求
     */
    private void updateCustomerPolicy() {
        PolicyHttps.getInstance(this.getApplicationContext()).updateCustomerPolicy(policyData, new PolicyHttps.onResponseCallback() {
            @Override
            public void onResponse(PolicyAllJson data) {
                Logger.i("->更新保单成功...");
                if (data != null && !TextUtils.isEmpty(data.policyId)) {
                    // 上传保单附件
                    List<Attachment> uploadEntitys = getUploadAttachments();
                    if (uploadEntitys != null && uploadEntitys.size() > 0) {
                        uploadCount = uploadEntitys.size();
                        uploadMultiAttach2AliYun(data.policyId, uploadEntitys);
                    } else {
                        // 没有需要上传的附件，也即没有需要提交的附件，则发送到创建完成
                        updateHandler.sendEmptyMessage(2);
                    }
                    // 删除保单附件
                    List<Attachment> deleteEntitys = getDeleteAttachments();
                    if (deleteEntitys != null && deleteEntitys.size() > 0) {
                        deletePolicyAttachments(data.policyId, deleteEntitys);
                    } else {
                        // 没有需要删除的附件，则发送到删除完成
                        updateHandler.sendEmptyMessage(1);
                    }
                }
//                EventBus.getDefault().post(new PolicyUpdateEvent(1, data.policyId));
//                finish();
            }

            @Override
            public void onError(ErrorJson error) {
                if (error != null) {
                    UIHelper.makeToast(PolicyEditActivity.this, getResources().getString(R.string.network_fail));
                }
            }

            @Override
            public void onFailure(Throwable t) {
                UIHelper.makeToast(PolicyEditActivity.this, getResources().getString(R.string.network_fail));
            }
        });
    }

    /**
     * 闪烁
     *
     * @param mode
     */
    private void flash(int mode) {
        for (MenuForPolicyEdit menu : mFlashMenus) {
            if (mode == 0) {
                menu.setBackgroundColor(Color.WHITE);
            } else if (mode == 1) {
                menu.setBackgroundColor(Color.parseColor("#fffff4f4"));
            }
        }
    }

    private void showDatePicker() {
        if (mDatePicker == null) {
            mDatePicker = new DatePickerDialog(PolicyEditActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                    String datePicked = i + "-" + (i1 + 1) + "-" + i2;
                    menuEffectDate.setContent(datePicked);
                    if (policyData != null) {
                        policyData.setEffectDate(datePicked);
                    }
                }
            },
                    Calendar.getInstance().get(Calendar.YEAR),
                    Calendar.getInstance().get(Calendar.MONTH),
                    Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        }
        mDatePicker.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.policy_details_back:
                // TODO 返回
                finish();
                break;
            case R.id.policy_details_complete:
                // TODO 完成
                if (!doClicking) {
                    doClicking = true;
                    doCheck();
                }
                break;
            case R.id.policy_details_brand:
                // TODO 品牌选择
                toCheckXX(0, null, policyData.getCompany() == null ? null : policyData.getCompany().getId());
                break;
            case R.id.policy_details_mainRisk:
                // TODO 主约选择
                if (policyData != null) {
                    if (policyData.getCompany() != null) {
                        toCheckXX(1, policyData.getCompany().getId(),
                                policyData.getRisk() == null ? null : policyData.getRisk().getId());
                    }
                }
                break;
            case R.id.policy_details_payMode:
                // TODO 缴费方式选择
                showDialog(0, Dictionary.PAY_PERIOD_LIST);
                break;
            case R.id.policy_details_relation:
                // TODO 与被保人关系选择
                break;
            case R.id.policy_details_effect:
                // TODO 选择生效日期
                showDatePicker();
                break;
        }
    }

    @Override
    public void onMenuSelect(int flag, int position, String content) {
        Toast.makeText(PolicyEditActivity.this, content, Toast.LENGTH_SHORT).show();
        if (flag == 0) {
            // TODO 缴费
            menuPayMode.setContent(content);
        } else if (flag == 1) {
            // TODO 关系
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        boolean clickAdding = mPicAdapter.isPositionForAdd(i);
        if (clickAdding) {
            // TODO 添加
            if (policyData == null || PolicyAttachOpt.isAllowingToAdd(policyData.getAttachments())) {
                toAdd();
            } else {
                UIHelper.makeToast(PolicyEditActivity.this, "最多允许添加5个附件");
            }
        } else {
            // TODO 预览
            toPreview(i);
        }
    }

    /**
     * 选择品牌或主约
     *
     * @param page
     * @param id
     */
    private void toCheckXX(int page, String id, String uuid) {
        Intent intent = new Intent(PolicyEditActivity.this, CheckCompanyOrRiskActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(CheckCompanyOrRiskActivity.EXTRA_PAGE, page);
        bundle.putString(CheckCompanyOrRiskActivity.EXTRA_PID, uuid);
        if (id != null) {
            bundle.putString(CheckCompanyOrRiskActivity.EXTRA_ID, id);
        }
        intent.putExtras(bundle);
        startActivityForResult(intent, page);
    }

    /* 点击附件（图片）预览*/
    private void toPreview(int pos) {
        Intent intent = new Intent(PolicyEditActivity.this, ImagePreviewActivity.class);
        Bundle data = new Bundle();
        data.putSerializable(ImagePreviewActivity.EXTRA_DATA, (Serializable) policyData.getAttachments());
        data.putInt(ImagePreviewActivity.EXTRA_POSITION, pos);
        data.putInt(ImagePreviewActivity.EXTRA_FLAG, 1);
        intent.putExtras(data);
        startActivity(intent);
    }

    /* 添加附件*/
    private void toAdd() {
      /*  if (processor == null) {
            processor = new ImageProcessor(PolicyEditActivity.this);
        }
        processor.showPicker();*/
        Matisse.from(PolicyEditActivity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    /**
     * 裁剪返回
     *
     * @param ev
     */
    @Subscribe
    public void onEvent(OnCropEvent ev) {
        List<Attachment> newAttachments = PolicyAttachOpt.addAttach(policyData.getAttachments(), ev.path);
        policyData.setAttachments(newAttachments);
        setGridAdapter();
    }

    /**
     * 移除附件返回
     *
     * @param ev
     */
    @Subscribe
    public void onEvent(OnAttachDeleteEvent ev) {
        policyData.setAttachments(ev.data);
        setGridAdapter();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
            // 选择'品牌'或'主险'后返回
            switch (requestCode) {
                case 0: // 品牌
                    CompanyBean company = (CompanyBean) data.getExtras().getSerializable(
                            CheckCompanyOrRiskActivity.EXTRA_DATA_FOR_RETURN);
                    if (company != null) {
                        menuBrand.setContent(company.getShortName());
                        // 品牌切换后，主险需要清空
                        menuRisk.clearContent();

                        if (policyData != null) {
                            policyData.setCompany(company);
                            policyData.setRisk(null);
                        }
                    }
                    break;
                case 1: // 主险
                    RiskBean risk = (RiskBean) data.getExtras().getSerializable(
                            CheckCompanyOrRiskActivity.EXTRA_DATA_FOR_RETURN);
                    if (risk != null) {
                        menuRisk.setContent(risk.getShortName());
                        if (policyData != null) {
                            policyData.setRisk(risk);
                        }
                    }
                    break;
                case REQUEST_CODE_CHOOSE:
                    List<Uri> chooseUris = Matisse.obtainResult(data);
                    if (chooseUris != null) {
                        for (Uri uri : chooseUris) {
                            if (uri != null) {
                                List<Attachment> newAttachments = PolicyAttachOpt.addAttach(policyData.getAttachments(),
                                        ImageSelectUtil.getPathFromUri(PolicyEditActivity.this, uri));
                                policyData.setAttachments(newAttachments);
                            }
                        }
                        setGridAdapter();
                    }
                    break;
            }
        }
        if (processor != null) {
            processor.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        updateHandler.removeCallbacksAndMessages(null);
        flashHandler.removeCallbacksAndMessages(null);
    }
}
